package com.woniu.sharepark.realm;

import com.woniu.sharepark.common.pojo.Login;
import com.woniu.sharepark.common.service.RoleService;
import com.woniu.sharepark.common.service.UserService;
import com.woniu.sharepark.platformsystem.pojo.Role;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import javax.annotation.Resource;
import java.util.HashSet;

/**
 * 自定义认证授权
 * @author SeaMonster
 * @date 2019/6/3 15:51
 * version v1.0
 */
public class CustomRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;



    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String lAccount= (String) principalCollection.getPrimaryPrincipal();
        Login login=userService.findUserByAccount(lAccount);
        Role role = roleService.selectByUserRid(login.getrId());
        HashSet set = new HashSet();
        set.add(role.getrName());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(set);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String account = (String) authenticationToken.getPrincipal();
        Login login = userService.findUserByAccount(account);
        if (login == null) {
            throw  new UnknownAccountException("unknown account");
        }
        ByteSource byteSource = ByteSource.Util.bytes(account);
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(account, login.getlPassword(), byteSource, this.getName());
        return authenticationInfo;
    }
}
